package com.dxb.idmr.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxb.idmr.entity.Papers;
import com.dxb.idmr.entity.Questions;
import com.dxb.idmr.entity.Students;
import com.dxb.idmr.entity.StudentsPapers;
import com.dxb.idmr.service.IPapersService;
import com.dxb.idmr.service.IQuestionsService;
import com.dxb.idmr.service.IStudentsPapersService;
import com.dxb.idmr.vo.CheckRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 试卷 前端控制器
 * </p>
 *
 * @author dxb
 * @since 2020-05-01
 */
@RestController
@RequestMapping("/papers")
public class PapersController {
    @Autowired
    IPapersService papersService;
    @Autowired
    IQuestionsService questionsService;
    @Autowired
    IStudentsPapersService studentsPapersService;
    @Autowired
    HttpServletRequest request;
    /**
     * 默认试卷ID
     */
    public static final long DEFALT_PAPER_ID = 1;

    @GetMapping("/questions")
    public List<Questions> getQuestionsByPaperId(Long id) throws Exception {
        List<Questions> questions = getAndValidate(id);
        for (Questions q : questions) {
            q.setRightAnswer(null);
        }
        return questions;
    }

    private List<Questions> getAndValidate(Long id) throws Exception {
        if (id == null || id == 0) {
            id = DEFALT_PAPER_ID;
        }
        Papers paper = papersService.getById(id);
        if (null == paper) {
            throw new Exception("没有找到试卷");
        }
        if (null == paper.getQuestions()) {
            throw new Exception("试卷没有题目");
        }
        List<Questions> questions = questionsService.listByIds(Arrays.asList(paper.getQuestions().split(",")));
        if (questions.isEmpty()) {
            throw new Exception("没有找到题目");
        }
        return questions;
    }

    @PostMapping("/check")
    public String checkPaper(@RequestBody CheckRequest checkRequest) throws Exception {
        Object attribute = request.getSession().getAttribute("student");
        if (null == attribute) {
            return "index";
        }
        Students students = (Students) attribute;
        Wrapper<StudentsPapers> sp = new QueryWrapper<StudentsPapers>()
                .eq("SNO", students.getSno());
        if (studentsPapersService.count(sp) > 0) {
            return "error?msg=不能重复提交";
        }

        StudentsPapers studentsPapers = new StudentsPapers();
        studentsPapers.setCreatedTime(LocalDateTime.now());
        studentsPapers.setSno(students.getSno());
        studentsPapers.setAnswer(checkRequest.getAnswers().toJSONString());
        studentsPapers.setRightCount(0);
        studentsPapers.setWrongCount(0);
        studentsPapers.setPaperId(checkRequest.getId());

        List<Questions> questions = getAndValidate(checkRequest.getId());
        for (Questions q : questions) {
            for (int i = 0; i < checkRequest.getAnswers().size(); i++) {
                JSONObject qq = checkRequest.getAnswers().getJSONObject(i);
                if (q.getId() == qq.getLong("id")) {
                    if (q.getRightAnswer().equals(qq.getString("rightAnswer"))) {
                        studentsPapers.setRightCount(studentsPapers.getRightCount() + 1);
                    } else {
                        studentsPapers.setWrongCount(studentsPapers.getWrongCount() + 1);
                    }
                    break;
                }
            }
        }
        studentsPapers.setScore(studentsPapers.getRightCount() * 100 / (studentsPapers.getRightCount() + studentsPapers.getWrongCount()));
        studentsPapersService.save(studentsPapers);
        return String.format("success?msg=考试成绩：%d分", studentsPapers.getScore());
    }
}
